package com.kb.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kb.entity.digikey.ProductData;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpRequest;
import com.kb.service.impl.DigikeyServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
@Slf4j
public class ProductDetailsFetcher {

    private static final int THREAD_POOL_SIZE = 10; // 可以根据需求调整


    public static List<ProductData> fetchProductDetails(List<String> productNumbers, String token, String currency) {
        List<CompletableFuture<ProductData>> futures = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();

        // 使用并行请求来获取产品详情
        for (String model : productNumbers) {
            CompletableFuture<ProductData> future = CompletableFuture.supplyAsync(() -> {
                try {
                    String replace = model.replace("/", "%2F").replace("#", "%23");


                    String jsonBody = "{"
                            + "\"KeyWord\": \"" + replace + "\","
                            + "\"Currency\": \"" + currency + "\","
                            + "\"token\": \"" + token + "\""
                            + "}";

// 创建 HttpRequest 实例
                    HttpRequest request = HttpRequest.post("http://8.155.30.82:5000/api/DigikeyApi/GetProductDetails")
                            .header("Content-Type", "application/json")  // 设置请求头
                            .timeout(60000)  // 设置超时时间
                            .body(jsonBody);  // 设置请求体

// 执行请求并获取响应
                    HttpResponse detailResponse = request.execute();

// 获取响应体并将其转换为对象
                    String detailResponseBody = detailResponse.body();
                    log.info(detailResponseBody);
                    return objectMapper.readValue(detailResponseBody, ProductData.class);

                } catch (Exception e) {
                    log.error("请求得捷详细错误，关键字为：" + model, e);
                    return null;
                }
            });

            futures.add(future);
        }

        // 等待所有请求完成并收集结果
        List<ProductData> result = new ArrayList<>();
        for (CompletableFuture<ProductData> future : futures) {
            try {
                ProductData productData = future.get(); // 获取每个异步请求的结果
                if (productData != null) {
                    result.add(productData);
                }
            } catch (InterruptedException | ExecutionException e) {
                log.error("获取产品详细信息失败", e);
            }
        }

        return result;
    }

}
